<template>
  <div class="component-upload-image">
    <a-upload
      multiple
      ref="imageUpload"
      list-type="picture-card"
      :limit="limit"
      :action="uploadImgUrl"
      :headers="headers"
      v-model:file-list="fileList"
      image-preview
      @success="handleUploadSuccess"
      :on-before-upload="handleBeforeUpload"
      :on-before-remove="handleDelete"
      @error="handleUploadError"
      @exceed-limit="handleExceed"
    />

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #cb272d">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #cb272d">{{ fileType.join('/') }}</b>
      </template>
      的文件{{ extraTip ? ', ' + extraTip : '' }}
    </div>
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth'
import { Modal, Message } from '@arco-design/web-vue'
const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['png', 'jpg', 'jpeg']
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  extraTip: {
    type: String,
    default: ''
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const number = ref(0)
const uploadList = ref([])
const dialogImageUrl = ref('')
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadImgUrl = ref(
  import.meta.env.VITE_APP_BASE_API + '/common/uploadByQiNiuYun'
) // 上传的图片服务器地址
const headers = ref({ Authorization: 'Bearer ' + getToken() })
const fileList = ref([])
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
)

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(',')
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === 'string') {
          item = { name: item, url: item }
        }
        return item
      })
    } else {
      fileList.value = []
      return []
    }
  },
  { deep: true, immediate: true }
)

// 上传前loading加载
function handleBeforeUpload(file) {
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      Message.error(`上传图片大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  number.value++
  return true
}

// 文件个数超出
function handleExceed() {
  Message.error(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传成功回调
function handleUploadSuccess(res) {
  if (res.response.code === 200) {
    uploadList.value.push({ name: res.name, url: res.response.data })
    uploadedSuccessfully()
  }
}

// 删除图片
function handleDelete(file) {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name)
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1)
    emit('update:modelValue', listToString(fileList.value))
    return false
  }
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit('update:modelValue', listToString(fileList.value))
  }
}

// 上传失败
function handleUploadError() {
  Message.error('上传图片失败')
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = ''
  separator = separator || ','
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf('blob:') !== 0) {
      strs += list[i].url.replace(baseUrl, '') + separator
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : ''
}
</script>

<style scoped lang="scss"></style>
